<?php

/**
 * 夏日葵电商系统
 * http://www.xiarikui.com
 */

namespace Mobile\Controller;

use Think\Page;

class AppDistributController extends MobileBaseController {

    public $user_id = 0;
    public $user = array();

    public function __construct() {
        parent::__construct();
        $user = session('user');
        $this->user = $user;
        $this->user_id = $user['user_id'];
        if (xrkCache('distribut')['switch'] < 1) {
            $this->error('系统关闭分销功能，请联系管理员', U('User/index'));
        }
//        if ($user['is_distribut'] < 1) {
//            $this->error('你不是分销商，请联系管理员', U('User/index'));
//        }
    }

    /**
     * 分销中心
     */
    public function index() {
        $this->assign('userInfo', $this->user);
        $this->assign('Rs', $this->order(true));
        $this->display();
    }

    /**
     * 分销佣金
     */
    public function commission() {
        $where = "user_id = {$this->user_id}";
        $passMoney = M('cash')->where($where . " and status=1")->sum('money');
        $unPassMoney = M('cash')->where($where . " and status=0")->sum('money');
        $this->assign('unPassMoney', $unPassMoney); //未通过审核佣金
        $this->assign('passMoney', $passMoney); //通过审核佣金
        $this->assign('distribut', xrkCache('distribut'));

        $this->assign('userInfo', $this->user);
        $this->assign('Rs', $this->order(true));
        $this->display();
    }

    /**
     * 我的团队
     */
    public function myTeam() {
        $userMod = M('users');
        $user = $this->user;
        $first = $userMod->where(array('first_leader' => $this->user_id))->field('user_id,nickname,level,reg_time,head_pic')->order('user_id desc')->select();
        $first_count = $userMod->where(array('first_leader' => $this->user_id))->count();

//        if ($user['level'] == 4) {
//            foreach ($first as $key => $value) {
//                if ($value['level'] == 3) {
//                    $first_count++;
//                }
//            }
        $second_count = $userMod->where(array('second_leader' => $this->user_id))->count();
//            $second = $userMod->where(array('second_leader' => $this->user_id))->field('user_id,nickname,level,reg_time,head_pic')->order('user_id desc')->select();
//            $second_count = 0;
//            foreach ($second as $key => $value) {
//                if ($value['level'] == 2) {
//                    $second_count++;
//                }
//            }
        $this->assign('second_count', $second_count);
//        } else if ($user['level'] == 3) {
//            foreach ($first as $key => $value) {
//                if ($value['level'] == 2) {
//                    $first_count++;
//                }
//            }
//        }
//        $third_count = $userMod->where(array('is_distribut' => 1, 'third_leader' => $this->user_id))->field('user_id,nickname,reg_time,head_pic')->order('user_id desc')->count();
        $this->assign('first_count', $first_count);
//        $this->assign('third_count', $third_count);
        $this->display();
    }

    /**
     * ajax我的团队
     */
    public function ajaxMyTeam() {
        $userMod = M('users');
        $level = I('level', 1);
        $count = I('teamCount');
        $user = $this->user;
        if ($user['level'] == 4) {
            if ($level == 1) {
                $page = new Page($count, 10);
                $rs = $userMod->where(array('first_leader' => $this->user_id))->field('user_id,nickname,level,reg_time,head_pic')->order('user_id desc')->limit($page->firstRow . ',' . $page->listRows)->select();
                if ($this->user_id == 305) {
                    
                }
            } elseif ($level == 2) {
                $page = new Page($count, 10);
                $rs = $userMod->where(array('second_leader' => $this->user_id))->field('user_id,nickname,level,reg_time,head_pic')->order('user_id desc')->limit($page->firstRow . ',' . $page->listRows)->select();
            }
        } elseif ($user['level'] == 3) {
            $page = new Page($count, 10);
            $rs = $userMod->where(array('first_leader' => $this->user_id))->field('user_id,nickname,level,reg_time,head_pic')->order('user_id desc')->limit($page->firstRow . ',' . $page->listRows)->select();
            foreach ($rs as $key => $value) {
                
            }
        }
//        $rs1 = $userMod->where(array('user_id' => $this->user_id))->field('first_leader')->find();
//        $this->assign('first_leader', $rs1['first_leader']);
//        elseif ($level == 3) {
//            $page = new Page($count, 10);
//            $rs = $userMod->where(array('is_distribut' => 1, 'third_leader' => $this->user_id))->field('user_id,nickname,reg_time,head_pic')->order('user_id desc')->limit($page->firstRow . ',' . $page->listRows)->select();
//        }
        $this->assign('rs', $rs);
        $this->display();
    }

    /**
     * 分销订单
     */
    public function order($is_return = false) {
        $userMod = M('users');
        $orderMod = M('Order');
        $user = $this->user;
        $first = $userMod->where(array('first_leader' => $this->user_id))->field('user_id,nickname,level,head_pic')->order('user_id desc')->select();
        if ($user['level'] == 4) {
            $second = $userMod->where(array('second_leader' => $this->user_id))->field('user_id,nickname,level,head_pic')->order('user_id desc')->select();
            $arr = array_merge($first, $second);
        } else if ($user['level'] == 3) {
            $arr = array_merge($first);
        }
        $where = ' 1=1 ';
        $idArr = array();
        $commission = 0;
        if (count($arr) > 0) {
            foreach ($arr as $key => $value) {
                array_push($idArr, $value['user_id']);
            }
            $idStr = implode(',', $idArr);
            $where .= " and user_id in ({$idStr}) ";
            $where1 = C('WAITPAY');
            $where2 = C('PAYED') . ' and order_status !=2 ';
            $where3 = ' and (order_status=2  or order_status=4) ';
            $order_str = " order_id DESC";
            $whereall = $where . " or ( {$where} {$where1}) or ( {$where}  {$where2}) or ( {$where}  {$where3})";
            $commission = $orderMod->where($whereall)->sum('order_amount');
            $unPayList = $orderMod->where($where . $where1)->field('order_id,user_id,order_sn,add_time,order_amount')->order($order_str)->select();
            $distributCon = xrkCache('distribut');
            $comm = $user['level'] == 4 ? $distributCon['first_rate'] : $distributCon['second_rate'];
            $unPayComm = 0;
            foreach ($unPayList as $key => $value) {
                $unPayComm = $value['order_amount'] * $comm / 100;
            }
            $payList = $orderMod->where($where . $where2)->field('order_id,user_id,order_sn,add_time,order_amount')->order($order_str)->select();
            $payComm = 0;
            foreach ($payList as $key => $value) {
                $payComm = $value['order_amount'] * $comm / 100;
            }
            $finishList = $orderMod->where($where . $where3)->field('order_id,user_id,order_sn,add_time,order_amount')->order($order_str)->select();
            $finishComm = 0;
            foreach ($finishList as $key => $value) {
                $finishComm = $value['order_amount'] * $comm / 100;
            }
            if (!$is_return) {
                $this->assign('sum', intval(count($unPayList) + count($payList) + count($finishList)));
                $this->assign('unPayList', count($unPayList));
                $this->assign('payList', count($payList));
                $this->assign('finishList', count($finishList));
            }
        } else {
            if (!$is_return) {
                $this->assign('sum', 0);
                $this->assign('unPayList', 0);
                $this->assign('payList', 0);
                $this->assign('finishList', 0);
            }
        }
        $distributCon = xrkCache('distribut');
        $comm = $user['level'] == 4 ? $distributCon['first_rate'] : $distributCon['second_rate'];
        if (!$is_return) {
            $this->assign('commission', round($commission * $comm / 100, 2));
            $this->display();
        } else {
            return array(
                'allComm' => round($commission * $comm / 100, 2),
                'unPayComm' => round($unPayComm, 2),
                'payComm' => round($payComm, 2),
                'finishComm' => round($finishComm, 2)
            );
        }
    }

    public function ajaxOrder($is_return = false, $type = 0) {
        $user = $this->user;
        $userMod = M('users');
        $orderMod = M('Order');
        $first = $userMod->where(array('first_leader' => $this->user_id))->field('user_id,nickname,level,head_pic')->order('user_id desc')->select();
        if ($user['level'] == 4) {
            $second = $userMod->where(array('second_leader' => $this->user_id))->field('user_id,nickname,level,head_pic')->order('user_id desc')->select();
            $arr = array_merge($first, $second);
        } elseif ($user['level'] == 3) {
            $arr = $first;
        }
//        $third = $userMod->where(array('is_distribut' => 1, 'third_leader' => $this->user_id))->field('user_id,nickname,level,head_pic')->order('user_id desc')->select();
        $where = ' 1=1 ';
//        $arr = array_merge($first, $second, $third);
        $idArr = array();
        $commission = 0;
        if (count($arr) > 0) {
            foreach ($arr as $key => $value) {
                array_push($idArr, $value['user_id']);
            }
            $idStr = implode(',', $idArr);
            $where .= " and user_id in ({$idStr}) ";
            $where1 = C('WAITPAY');
            $where2 = C('PAYED') . ' and order_status !=2 ';
            $where3 = ' and (order_status=2  or order_status=4) ';
            $whereall = $where . " or ( {$where} {$where1}) or ( {$where}  {$where2}) or ( {$where}  {$where3})";
            $order_str = " order_id DESC";

            $distributCon = xrkCache('distribut');
            $comm = $user['level'] == 4 ? $distributCon['first_rate'] : $distributCon['second_rate'];
//            dump($distributCon);
            $count = I('teamCount');
            $type = I('type');
            if ($type == 0) {
                $page = new Page($count, 10);
                $List = $orderMod->where($whereall)->field('order_id,user_id,order_sn,add_time,order_amount,order_status,shipping_status,pay_status,pay_code')->select();
                foreach ($List as $k => $v) {
                    if ($v['pay_status'] == 0 && $v['order_status'] == 0 && $v['pay_code'] != 'cod') {
                        $List[$k]['type'] = '未付款';
                    } else if ($v['order_status'] == 1) {
                        $List[$k]['type'] = '已付款';
                    } else {
                        $List[$k]['type'] = '已完成';
                    }
                    foreach ($first as $key => $value) {
                        if ($value['user_id'] == $v['user_id']) {
                            $List[$k]['level'] = $user['level'] == 4 ? '黄金' : '白银';
                            $List[$k]['nickname'] = $value['nickname'];
                            $List[$k]['head_pic'] = $value['head_pic'];
                            $List[$k]['commission'] = floatval($v['order_amount'] * $comm / 100); //佣金
                            $commission += $List[$k]['commission'];
                        }
                    }
                    if ($user['level'] == 4) {
                        foreach ($second as $key => $value) {
                            if ($value['user_id'] == $v['user_id']) {
                                $List[$k]['level'] = '白银';
                                $List[$k]['nickname'] = $value['nickname'];
                                $List[$k]['head_pic'] = $value['head_pic'];
                                $List[$k]['commission'] = floatval($v['order_amount'] * $distributCon['first_rate'] / 100); //佣金
                                $commission += $List[$k]['commission'];
                            }
                        }
                    }
//                    foreach ($third as $key => $value) {
//                        if ($value['user_id'] == $v['user_id']) {
//                            $List[$k]['level'] = '三级';
//                            $List[$k]['nickname'] = $value['nickname'];
//                            $List[$k]['head_pic'] = $value['head_pic'];
//                            $List[$k]['commission'] = floatval($v['order_amount'] *  $distributCon['third_rate'] /100); //佣金
//                            $commission += $List[$k]['commission'];
//                        }
//                    }
                }
                $this->assign('rs', $List);
            } elseif ($type == 1) {
                $page = new Page($count, 10);
                $unPayList = $orderMod->where($where . $where1)->field('order_id,user_id,order_sn,add_time,order_amount')->order($order_str)->select();
                foreach ($unPayList as $k => $v) {
                    foreach ($first as $key => $value) {
                        if ($value['user_id'] == $v['user_id']) {
                            $unPayList[$k]['level'] = $user['level'] == 4 ? '黄金' : '白银';
                            $unPayList[$k]['nickname'] = $value['nickname'];
                            $unPayList[$k]['head_pic'] = $value['head_pic'];
                            $unPayList[$k]['commission'] = floatval($v['order_amount'] * $comm / 100); //佣金
                            $commission += $unPayList[$k]['commission'];
                            $unPayList[$k]['type'] = '未付款';
                        }
                    }
                    if ($user['level'] == 4) {
                        foreach ($second as $key => $value) {
                            if ($value['user_id'] == $v['user_id']) {
                                $unPayList[$k]['level'] = '白银';
                                $unPayList[$k]['nickname'] = $value['nickname'];
                                $unPayList[$k]['head_pic'] = $value['head_pic'];
                                $unPayList[$k]['commission'] = floatval($v['order_amount'] * $distributCon['first_rate'] / 100); //佣金
                                $commission += $unPayList[$k]['commission'];
                                $unPayList[$k]['type'] = '未付款';
                            }
                        }
                    }
//                    foreach ($third as $key => $value) {
//                        if ($value['user_id'] == $v['user_id']) {
//                            $unPayList[$k]['level'] = '三级';
//                            $unPayList[$k]['nickname'] = $value['nickname'];
//                            $unPayList[$k]['head_pic'] = $value['head_pic'];
//                            $unPayList[$k]['commission'] = floatval($v['order_amount'] *  $distributCon['third_rate'] /100); //佣金
//                            $commission += $unPayList[$k]['commission'];
//                            $unPayList[$k]['type'] = '未付款';
//                        }
//                    }
                }
                $this->assign('rs', $unPayList);
            } elseif ($type == 2) {
                $page = new Page($count, 10);
                $payList = $orderMod->where($where . $where2)->field('order_id,user_id,order_sn,add_time,order_amount')->order($order_str)->select();
//                dump($payList);
                foreach ($payList as $k => $v) {
                    foreach ($first as $key => $value) {
                        if ($value['user_id'] == $v['user_id']) {
                            $payList[$k]['level'] = $user['level'] == 4 ? '黄金' : '白银';
                            $payList[$k]['nickname'] = $value['nickname'];
                            $payList[$k]['head_pic'] = $value['head_pic'];
                            $payList[$k]['commission'] = floatval($v['order_amount'] * $comm / 100); //佣金
                            $commission += $payList[$k]['commission'];
                            $payList[$k]['type'] = '已付款';
                        }
                    }
                    if ($user['level'] == 4) {
                        foreach ($second as $key => $value) {
                            if ($value['user_id'] == $v['user_id']) {
                                $payList[$k]['level'] = '白银';
                                $payList[$k]['nickname'] = $value['nickname'];
                                $payList[$k]['head_pic'] = $value['head_pic'];
                                $payList[$k]['commission'] = floatval($v['order_amount'] * $distributCon['first_rate'] / 100); //佣金
                                $commission += $payList[$k]['commission'];
                                $payList[$k]['type'] = '已付款';
                            }
                        }
                    }
//                    foreach ($third as $key => $value) {
//                        if ($value['user_id'] == $v['user_id']) {
//                            $payList[$k]['level'] = '三级';
//                            $payList[$k]['nickname'] = $value['nickname'];
//                            $payList[$k]['head_pic'] = $value['head_pic'];
//                            $payList[$k]['commission'] = floatval($v['order_amount'] *  $distributCon['third_rate'] /100); //佣金
//                            $commission += $payList[$k]['commission'];
//                            $payList[$k]['type'] = '已付款';
//                        }
//                    }
                }
                $this->assign('rs', $payList);
            } elseif ($type == 3) {
                $page = new Page($count, 10);
                $finishList = $orderMod->where($where . $where3)->field('order_id,user_id,order_sn,add_time,order_amount')->select();
                foreach ($finishList as $k => $v) {
                    foreach ($first as $key => $value) {
                        if ($value['user_id'] == $v['user_id']) {
                            $finishList[$k]['level'] = $user['level'] == 4 ? '黄金' : '白银';
                            $finishList[$k]['nickname'] = $value['nickname'];
                            $finishList[$k]['head_pic'] = $value['head_pic'];
                            $finishList[$k]['commission'] = floatval($v['order_amount'] * $comm / 100); //佣金
                            $commission += $finishList[$k]['commission'];
                            $finishList[$k]['type'] = '已完成';
                        }
                    }
                    if ($user['level'] == 4) {
                        foreach ($second as $key => $value) {
                            if ($value['user_id'] == $v['user_id']) {
                                $finishList[$k]['level'] = '白银';
                                $finishList[$k]['nickname'] = $value['nickname'];
                                $finishList[$k]['head_pic'] = $value['head_pic'];
                                $finishList[$k]['commission'] = floatval($v['order_amount'] * $distributCon['first_rate'] / 100); //佣金
                                $commission += $finishList[$k]['commission'];
                                $finishList[$k]['type'] = '已完成';
                            }
                        }
                    }
//                    foreach ($third as $key => $value) {
//                        if ($value['user_id'] == $v['user_id']) {
//                            $finishList[$k]['level'] = '三级';
//                            $finishList[$k]['nickname'] = $value['nickname'];
//                            $finishList[$k]['head_pic'] = $value['head_pic'];
//                            $finishList[$k]['commission'] = floatval($v['order_amount'] *  $distributCon['third_rate'] /100); //佣金
//                            $commission += $finishList[$k]['commission'];
//                            $finishList[$k]['type'] = '已完成';
//                        }
//                    }
                }
                $this->assign('rs', $finishList);
            }
        } else {
            $this->assign('sum', 0);
            $this->assign('unPayList', array());
            $this->assign('payList', array());
            $this->assign('finishList', array());
        }
        if (!$is_return) {
            $this->assign('commission', round($commission, 2));
            $this->display();
        } else {
            return round($commission, 2);
        }
    }

    /**
     * 二维码
     */
    public function qrcode() {
        $userId = $this->user_id;
//        if (!file_exists("Public/upload/qrcode/qrcode_{$userId}.png")) {
        $this->createCode();
//        }
        $this->assign('user_id', $userId);
        $this->display();
    }

    /**
     * 创建二维码
     */
    public function createCode() {
        Vendor('phpqrcode.phpqrcode');
        $level = 1; //容错级别
        $size = 5; //生成图片大小

        $userId = $this->user_id;
        $apply_level = D('UserInfo')->where(array('user_id' => $userId))->getField('apply_level');
        if (!empty($apply_level)) {
            $url = SITE_URL . "/index.php/Mobile/Loginbind/register/level/{$apply_level}/user_id/{$userId}.html"; // U('Mobile/AppDistribut/followDistribut', array('user_id', $userId));
        } else {
            $url = SITE_URL . "/index.php/Mobile/Loginbind/register/user_id/{$userId}.html"; // U('Mobile/AppDistribut/followDistribut', array('user_id', $userId));
        }
//保存的路径+图片名
        $QRname = "Public/upload/qrcode/qrcode_{$userId}.png";
        \QRcode::png($url, $QRname, $level, $size, 2);
        $user = $this->user;
        $logo = SITE_URL . '/Public/upload/qrcode/logo.png';
        $QR = imagecreatefromstring(file_get_contents($QRname));
        $logo = imagecreatefromstring(file_get_contents($logo));
        $QR_width = imagesx($QR); //二维码图片宽度
        $QR_height = imagesy($QR); //二维码图片高度
        $logo_width = imagesx($logo); //logo图片宽度
        $logo_height = imagesy($logo); //logo图片高度
        $logo_qr_width = $QR_width / 5;
        $scale = $logo_width / $logo_qr_width;
        $logo_qr_height = $logo_height / $scale;
        $from_width = ($QR_width - $logo_qr_width) / 2;
//重新组合图片并调整大小
        imagecopyresampled($QR, $logo, $from_width, $from_width, 0, 0, $logo_qr_width, $logo_qr_height, $logo_width, $logo_height);
//输出图片
        unlink($QRname);
        imagepng($QR, $QRname);
    }

    /**
     * 关注、成为下线
     */
    public function followDistribut() {
        header("Content-type:text/html;charset=utf-8");
        $user_id = I('get.user_id'); //被扫分销商
        $userId = $this->user_id;
        if (intval($userId) !== intval($user_id)) {
            $userMod = M('users');
            $user = $userMod->where(array('user_id' => $user_id))->find();
            $user1 = $userMod->where(array('user_id' => $userId))->find();
            if (empty($user1['first_leader'])) {
                $data['first_leader'] = $user_id;
                $data['second_leader'] = $user['first_leader'];
                $data['third_leader'] = $user['second_leader'];
                $userMod->where(array('user_id' => $userId))->save($data);
            }
            echo "<script>alert('扫描成功!');location.href='" . SITE_URL . "/index.php/Mobile/Index/index';</script>";
        }
    }

    /**
     * 为下级申请分销
     */
    public function ajaxApply() {
        $applyId = I('apply_id');
        if (empty($applyId)) {
            $this->error('参数错误!', U('Mobile/AppDistribut/myTeam'));
        }
        $applyMod = D('AppDistributApply');
        $rs = $applyMod->where(array('apply_id' => $applyId, 'user_id' => $this->user_id))->find();
        if (!empty($rs)) {
            $this->error('已经申请了', U('Mobile/AppDistribut/myTeam'));
        } else {
            $data['apply_id'] = $applyId;
            $data['user_id'] = $this->user_id;
            $data['status'] = 1;
            $insert_id = $applyMod->add($data);
            if ($insert_id) {
                $this->ajaxReturn(array('status' => 1, 'msg' => '申请成功!', 'url' => U('Mobile/AppDistribut/myTeam')));
            } else {
                $this->ajaxReturn(array('status' => 0, 'msg' => '申请失败!', 'url' => U('Mobile/AppDistribut/myTeam')));
            }
        }
    }

}
